|
|
|
|
|
|
|
A counter loop is also known as a For loop, or a For/Next loop, because the ends of the loop are defined by the For statement and the Next statement. At the beginning of a For loop, you define a counter variable, as well as the beginning and end points of the variable's value, and optionally the Step value, or the amount it is to be increased or decreased after each pass through the loop. The first time the loop is run, the counter variable is set to the value of the beginning point. Then, after each time the program runs through the loop, the value of the counter is incremented by the Step value and checked against the value of the endpoint. If the counter is larger than the end point, the program skips to the first statement following the loop's Next statement |
|
|
|
|
CAUTION
|
|
|
|
|
If the beginning value of the loop is greater than the ending value, the loop does not execute at all. The exception is if you set up the loop to count backward, by setting the Step value to a negative number. In this case, the loop executes until the counter variable is less than the end point. |
|
|
|
|
|
|
| |
|
|
|
|
For ease of reading your program, including the variable name in the Next statement is good practice. Adding the name is especially important in nested loops. |
|
|
|
|
|
|
CAUTION
|
|
|
|
|
Although you can use any numeric variable for the counter, you need to be aware of the limits of variable types. For example, trying to run a loop 40,000 times using an integer variable causes an error during execution because an integer has a maximum value of 32,767. The limits of each variable type are documented in the Help file in a topic titled "Data Type Summary." |
|
|
|
|
|
|
|
|
|
|
The following code illustrates using a For/Next loop to print on the printer the numbers 1 through 10 and their squares: |
|
|
|
|
|
|
|
|
For i = 1 To 10
sTemp = i & " squared is " & (i * i)
Printer.Print sTemp
Next i |
|
|
|
|
|
|
|
|
The next example shows the use of a For/Next loop to reset the elements of three variable arrays to zero. Iterative processing allows these few lines of code to take the place of many. Using For/Next loops in conjunction with arrays in this manner is quite common: |
|
|
|
|
|
|
|
|
For i = 1 To 12
fMonthSales(i) = 0
fMonthExpenses(i) = 0
fMonthProfit(i) = 0
Next i |
|
|
|
|
|